<!--
 * @Author: LiYuan
 * @Date: 2021-04-07 09:56:00
 * @LastEditTime: 2021-07-29 10:00:35
 * @LastEditors: LiYuan
 * @Description: 保存到现有客户/维护客户信息
 * You build it, You run it.
-->
<template>
  <!-- 保存到现有客户 -->
  <base-modal :show.sync="visible" :title="$t('event.detail.components.eventButtonGroup.text11')" width="600px" class="save-to-exist-customer-dialog">
    <div class="base-modal-content">
      <el-form label-position="top" :model="form" :rules="rules" ref="cusSaveExistRef">
        <el-form-item :label="$t('common.base.customer')" prop="customer">
          <span v-if="cusExist">{{workEvent.cusName}}</span>
          <div v-else>
            <biz-search-customer-select
              :placeholder="$t('event.detail.components.dialog.text51')"
              :remote-method="remoteMethod"
              :value="form.customer"
              clearable
              @input="updateSelectValue">
            </biz-search-customer-select>
          </div>
        </el-form-item>
        <el-form-item :label="$t('common.base.contact')" prop="linkmen">
          <el-select :value="form.linkmen" value-key="id" @change="linkmenChange" :placeholder="$t('product.form.tips.tip7')" style="width: 100%">
            <el-option
              v-for="item in linkmenOptions"
              :key="item.id"
              :label="item.label"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.base.locationMap.address')" prop="address">
          <el-select :value="form.address" value-key="id" @change="addressChange" :placeholder="$t('product.form.tips.tip7')" style="width: 100%">
            <el-option
              v-for="item in addressOptions"
              :key="item.id"
              :label="item.label"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <base-button type="primary" @event="saveExistCustomer" :loading="loading">{{$t('common.base.makeSure')}}</base-button>
    </div>
  </base-modal>
</template>

<script>
import * as EventApi from '@src/api/EventApi.js';
import { formatAddress } from 'pub-bbx-utils';
export default {
  name: 'save-to-exist-customer-dialog',
  props:{
    workEvent: {
      type: Object,
      default: () => {}
    },
    isAddressAllowNull: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      rules: {
        customer: [
          { required: true, message: this.$t('common.placeholder.selectCustomer'), trigger: 'change' },
        ],
        linkmen: [
          { required: true, message: this.$t('common.placeholder.selectContact'), trigger: 'change' },
        ],
        // address: [
        //   { required: true, message: '请选择地址', trigger: 'change' },
        // ],
      },
      form: {
        // linkmen: {},
        // address: {}
      },
      visible: false,
      loading: false,
      cusExist: false,
      isConvert2Task: false,
      linkmenOptions: [],
      addressOptions: [],
    }
  },
  methods: {
    /**
     * @description: 
     * @param {*} customerId
     * @param {*} isConvert2Task 创建工单convert2TaskNew需要校验 workEvent.validAddress
     * @return {*}
     */
    openDialog(customerId, isConvert2Task) {
      if(customerId) {
        this.cusExist = true
        this.$set(this.form, 'customer', [{
          id: customerId,
          value: customerId,
          name: this.workEvent.cusName
        }])
        this.getLinkAndAddress(customerId)
      } else {
        this.cusExist = false
      }
      if(isConvert2Task) this.isConvert2Task = isConvert2Task
      this.visible = true;
    },
    
    async remoteMethod(params) {
      const pms = params || {};

      return await EventApi.eventGetList4Convert(pms)
        .then((res) => {
          if (!res || !res.list) return;

          res.list = res.list.map((customer) =>
            Object.freeze({
              label: customer.name,
              value: customer.id,
              ...customer,
            })
          );
          return res;
        })
        .catch((e) => console.error(e));
    },

    updateSelectValue(value) {
      this.$set(this.form, 'customer', value)
      const customerId = value[0].id
      this.getLinkAndAddress(customerId)
    },

    linkmenChange(value) {
      this.$set(this.form, 'linkmen', value)
    },

    addressChange(value) {
      this.$set(this.form, 'address', value)
    },

    getLinkAndAddress(customerId) {
      const params = {
        customerId: customerId
      }
      EventApi.eventGetInfo4CusChange(params)
        .then(res => {
          // 联系人
          let linkmanList = res.linkmanList;
          let linkmenOptions = [];
          let matchedLmId; // 如果事件上的联系人信息没有在返回的list里出现，则需要加一个无id的option
          let defaultLinkman;
          const EventLinkmen = `${this.workEvent.lmName} ${this.workEvent.lmPhone || this.workEvent.lmEmail || ''}`;
          linkmanList.forEach(linkman => {
              let label = linkman.name+" "+(linkman.phone || linkman.email || '');
              if(label == EventLinkmen) {
                matchedLmId = linkman.id;
                defaultLinkman = linkman
              }
              linkmenOptions.push({id:linkman.id, value:linkman.id, label:label});
          })
          
          if(!matchedLmId) {
            if(this.isConvert2Task && !this.workEvent.validAddress ) return
            linkmenOptions.unshift({id:'needAdd', value:'needAdd', label: EventLinkmen});
            defaultLinkman = linkmenOptions[0];
          }
          this.linkmenOptions = linkmenOptions
          this.$set(this.form, 'linkmen', defaultLinkman)

          // 地址
          let addressList = res.addressList || [];
          let addressOptions = [];
          let matchedAddId; // 如果事件上的地址信息没有在返回的list里出现，则需要加一个无id的option
          let defaultAddress;
          const customerAddress = this.workEvent?.cusAddress || {} 
          const { province, city, dist, address } = customerAddress
          const EventAddress = [ province, city, dist, address ].filter(Boolean).join(' ')
          addressList.forEach((address, idx) => {
            const label = formatAddress(address,'-');
            if(label == EventAddress) {
                matchedAddId = address.id;
                defaultAddress = address;
            }
            addressOptions.push({id:address.id,  value:address.id, label:label});
          })
          // conver2Task需要validAddress
          const judgeBoolean = this.isConvert2Task ? !matchedAddId && this.workEvent.validAddress == 'true' : !matchedAddId
          if(judgeBoolean) {
            addressOptions.unshift({ id: 'needAdd', value: 'needAdd', label: EventAddress });
            defaultAddress = addressOptions[0];
          }
          this.addressOptions = addressOptions
          this.$set(this.form, 'address', defaultAddress)
        })
        .catch(err => {
          console.error(err)
        })
    },

    // 确认保存为现有客户
    saveExistCustomer() {
      this.$refs.cusSaveExistRef.validate((vali) => {
        if(vali) {
          if(this.form.address && !this.form.address.id && !this.isAddressAllowNull) {
            this.$message.warning(this.$t('common.placeholder.selectAddress'))
            return
          }
          let params = {
            eventId: this.workEvent.id,
            customerId: this.form.customer[0].id,
            linkmanId: this.form?.linkmen?.id,
            addressId: this.form?.address?.id,
          }
          if(params.linkmanId == 'needAdd') params.linkmanId = null
          if(params.addressId == 'needAdd') params.addressId = null
          this.loading = true
          EventApi.eventUpdate4CusInfo(params)
            .then(res => {
              if(res.status == 0) {
                this.$emit('success')
              } else {
                this.$notify({
                  title: this.$t('common.base.error'),
                  message: res.message,
                  type: 'error'
                });
              }
              this.loading = false
            })
            .catch(err => {console.error(err)})
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.base-modal-content {
  padding: 20px;
}

.is-required:before {
  content: '';
}
</style>